<?php
namespace app\index\controller;

use think\Controller;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use app\index\model\Excels as Excels;

class Index extends Controller
{
    public function index() {
        return $this->fetch('index');
    }

    public function update()
    {
        //获取表格的大小，限制上传表格的大小5M
        if(isset($_FILES['inputExcelclass'])){
            $file_size = $_FILES['inputExcelclass']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                $this->error('文件大小不能超过5M');
                exit();
            }
        }
        //限制上传表格类型
        if(isset($_FILES['inputExcelclass'])){
            $fileExtendName = substr(strrchr($_FILES['inputExcelclass']["name"], '.'), 1);
        }
        //application/vnd.ms-excel  为xls文件类型
        if ($fileExtendName != 'xls' && $fileExtendName != 'xlsx') {
            $this->error('必须为excel表格，且必须为xls格式！');
            exit();
        }
        // 有Xls和Xlsx格式两种
        if( $fileExtendName =='xlsx' )
        {
            $objReader = IOFactory::createReader('Xlsx');
        }else{
            $objReader = IOFactory::createReader('Xls');
        }
        $objReader->setReadDataOnly(TRUE);
        $filename = $_FILES['inputExcelclass']['tmp_name'];
        $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
        $sheet = $objPHPExcel->getSheet(1);   //excel中的第二张sheet（0表示第一张）
        $highestRow = $sheet->getHighestRow();       // 取得总行数
        $highestColumn = $sheet->getHighestColumn();   // 取得总列数
        \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
        $lines = $highestRow -1;
        if($lines <= 0){
            $this->error('excel表格，没有数据！');
        }
        //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
        for ($j = 2; $j <= $highestRow; $j++) {
            $data[$j - 2] = [
                'username' => trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue()),
                'start_time' => trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()),
            ];
        }
        //使用模型
        $excels = new Excels();
        $res = $excels->saveAll($data);
        if ($res) {
            $this->success('上传成功！');
        }

    }

    //删除
    public function del() {
        $res = Excels::destroy(true);
        if ($res) {
            $this->success('删除成功','index/index/index');
        }
    }

}
